package com.kly.sc.api.integration.im.impl;

import com.alibaba.fastjson.JSON;
import com.kly.sc.api.infras.enums.RestCodeEnum;
import com.kly.sc.api.infras.exception.ApplicationException;
import com.kly.sc.api.integration.im.RCClient;
import com.kly.sc.api.integration.im.RCConfig;
import com.kly.sc.api.integration.im.RCInvokeHelper;
import io.rong.RongCloud;
import io.rong.RongCloudConfig;
import io.rong.methods.user.User;
import io.rong.methods.user.blacklist.Blacklist;
import io.rong.methods.user.onlinestatus.OnlineStatus;
import io.rong.models.Result;
import io.rong.models.message.MessageModel;
import io.rong.models.message.PrivateMessage;
import io.rong.models.response.*;
import io.rong.models.user.UserModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;

/**
 * 调用融云服务客户端
 * @author linqu
 */
@Service
@Slf4j
public class RCClientImpl implements RCClient {

    @Resource
    RCConfig rcConfig;
    /**
     * 融云平台客户端
     */
    private RongCloud rongCloud;
    /**
     * 融云平台用户调用类
     */
    private User rcUser;
    /**
     * 融云平台黑名单调用实体
     */
    private Blacklist blackListCaller;

    private OnlineStatus onlineStatus;

    private io.rong.methods.message._private.Private Private;
    private io.rong.methods.message.system.MsgSystem MsgSystem;



    @PostConstruct
    public void init() {
        String apiUrlStr = rcConfig.getApiUrl();
        if (StringUtils.isEmpty(apiUrlStr)) {
            log.error("RCClient initialization failed: The apiUrl should not be empty");
            throw new ApplicationException(RestCodeEnum.RC_CONFIG_ERROR);
        }

        rongCloud = RongCloud.getInstance(rcConfig.getApiKey(), rcConfig.getApiSecret(), new RongCloudConfig(apiUrlStr));
        rcUser = rongCloud.user;
        blackListCaller = rongCloud.user.blackList;
        onlineStatus = rongCloud.user.onlineStatus;
        Private = rongCloud.message.msgPrivate;
        MsgSystem = rongCloud.message.system;
    }


    /**
     * api文档地址：https://doc.rongcloud.cn/imserver/server/v1/user/register
     * 功能描述:注册并获取token 通过调用sdk的方式
     * @param userCode 用户内码
     * @param name 名称
     * @param portraitUri 用户头像
     * @return 连接token
     */
    @Override
    public TokenResult register(String userCode, String name, String portraitUri) {
        return RCInvokeHelper.getData(() -> {
            UserModel user = new UserModel().setId(userCode).setName(name).setPortrait(portraitUri);
            return rcUser.register(user);
        });
    }

    /**
     * api文档地址：https://doc.rongcloud.cn/imserver/server/v1/user/modify
     * 功能描述：修改用户信息
     * @param userCode 用户id
     * @param name     昵称
     * @param portraitUri 头像地址
     * @return
     */
    @Override
    public Result modifyUser(String userCode, String name, String portraitUri) {
        return RCInvokeHelper.getData(() -> {
            UserModel user = new UserModel().setId(userCode).setName(name).setPortrait(portraitUri);
            return rcUser.update(user);
        });
    }

    /**
     * api文档地址：https://doc.rongcloud.cn/imserver/server/v1/user/get
     * 功能描述：获取用户信息
     *
     * @param userCode 用户id
     * @return
     */
    @Override
    public UserResult getUserInfo(String userCode) {
        return RCInvokeHelper.getData(() -> {
            UserModel user = new UserModel().setId(userCode);
            return rcUser.get(user);
        });
    }

    /**
     * api文档地址：https://doc.rongcloud.cn/imserver/server/v1/user/check-online-status-by-user
     * 功能描述：查询用户在线状态
     *
     * @param userCode 用户id
     * @return
     */
    @Override
    public CheckOnlineResult checkOnlineStatusByUser(String userCode) {

        return RCInvokeHelper.getData(() -> {
            UserModel user = new UserModel().setId(userCode);
            return onlineStatus.check(user);
        });
    }

    /**
     * api文档地址：https://doc.rongcloud.cn/imserver/server/v1/user/add-to-blacklist
     * 功能描述：用户添加黑名单
     *
     * @param userCode
     * @param blackUserCodes
     * @return
     */
    @Override
    public Result addBlackList(String userCode, List<String> blackUserCodes) {
        return RCInvokeHelper.getData(() -> {
            UserModel[] blacklist = new UserModel[blackUserCodes.size()];
            int i = 0;
            for (String blackUserId : blackUserCodes) {
                UserModel userModel = new UserModel().setId(blackUserId);
                blacklist[i++] = userModel;
            }

            UserModel user = new UserModel().setId(userCode).setBlacklist(blacklist);

            return blackListCaller.add(user);
        });
    }

    /**
     * api文档地址：https://doc.rongcloud.cn/imserver/server/v1/user/query-blacklist
     * 功能描述：查询用户黑名单
     *
     * @param userCode
     * @return
     */
    @Override
    public BlackListResult queryBlackList(String userCode) {
        return RCInvokeHelper.getData(() -> {
            UserModel user = new UserModel().setId(userCode);
            return blackListCaller.getList(user);
        });
    }

    /**
     * api文档地址：https://doc.rongcloud.cn/imserver/server/v1/user/remove-from-blacklist
     * 功能描述：用户移除黑名单
     *
     * @param userCode
     * @param blackUserCodes
     * @return
     */
    @Override
    public Result removeBlackList(String userCode, List<String> blackUserCodes) {
        return RCInvokeHelper.getData(() -> {
            UserModel[] blacklist = new UserModel[blackUserCodes.size()];

            int i = 0;
            for (String blackUserId : blackUserCodes) {
                UserModel userModel = new UserModel().setId(blackUserId);
                blacklist[i++] = userModel;
            }
            UserModel user = new UserModel().setId(userCode).setBlacklist(blacklist);

            return blackListCaller.remove(user);
        });
    }

    /**
     * 消息发送
     * @param privateMessage
     * @return
     */
    @Override
    public ResponseResult sendPrivateMessage(PrivateMessage privateMessage) {
        final ResponseResult result = RCInvokeHelper.getData(() -> Private.send(privateMessage));
        log.info("RCClient.sendPrivateMessage.result:{}", result);
        return result;
    }

    @Override
    public ResponseResult sendPublishMessage(MessageModel messageModel){
        final ResponseResult result = RCInvokeHelper.getData(() -> MsgSystem.send(messageModel));
        log.info("RCClient.sendPublishMessage.result:{}", result);
        return result;
    }
}
